package com.lib;

import java.io.File;

import android.content.Context;
import android.os.Environment;

public class FileCache {
	static FileCache fc = new FileCache();

	public static FileCache getCache() {
		return fc;
	}

	File root;
	final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
	final int cacheSize = maxMemory / 2;
	private LruCache<String, File> lruCache = new LruCache<String, File>(
			cacheSize) {
		protected void entryRemoved(boolean evicted, String key, File oldValue,
				File newValue) {
			oldValue.delete();
		}

		protected int sizeOf(String key, File value) {
			return (int) value.length();
		}

		@Override
		protected File create(String key) {
			File file = getFile(key);
			return file.exists() ? file : null;
		}
	};

	public File getFile(String key) {
		return new File(root, key);
	}

	FileCache() {
		root = createFilePath(BaseApplication.getInstance().getContext(), "bitmap");
		if(!root.exists()){
			root.mkdirs();
		}
		File[] file = root.listFiles();
		if (file != null) {
			for (int i = file.length; --i >= 0;) {
				lruCache.put(file[i].getName(), file[i]);
			}
		}
	}

	private static File createFilePath(Context context, String cacheName) {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return new File(context.getExternalCacheDir(), cacheName);
		} else {
			return new File(context.getCacheDir(), cacheName);
		}
	}

	public File get(String key) {
		return lruCache.get(key);
	}

	public void put(String key, File value) {
		lruCache.put(key, value);
	}
}
